import os
from flask import Flask, request, jsonify
from flask_cors import CORS
from search import send_to_queue, get_date_content_by_id, redis_connection
from http import HTTPStatus
import uuid, json, time, redis, dashscope
dashscope.api_key="sk-93f72020b4ee4cba82580ccc43557337"
import ssl

app = Flask(__name__)
CORS(app)

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile='acapp.pem', keyfile='acapp.key')

@app.route("/search/query_es", methods=['POST'])
def query_es():
    """ 查询函数
        :query: 检索词
        :new_json: 最终json字符串
        :new_data_list: 近似词json字符串
        :count_num: 检索到的条数
        :json_list: new_json去重后json字符串
        :return: 检索词+关键词json字符串
    """
    task_id = str(uuid.uuid4())
    data = request.json

    # 解析传入的数据
    query = data.get('query', None)
    level = data.get('level', None)
    province = data.get('province', None)
    city = data.get('city', None)
    source = data.get('source', None)
    tag = data.get('tag', None)
    page = data.get('page', None)
    starttime = data.get('starttime', None)
    endtime = data.get('endtime', None)
    if not page:
        page = 1
    else:
        page = int(page)

    # 将任务发送到RabbitMQ队列中
    send_to_queue(task_id, query, level, province, city, source, tag, page, starttime, endtime)

    return jsonify({'code': 200, 'msg': "Query task sent to RabbitMQ for processing", 'uuid': task_id})


@app.route("/search/query_result", methods=['POST'])
def query_result():
    """ 获取查询结果函数
        :uuid: 每条查询的唯一 id
        :return: uuid + 查询结果
    """
    request_data = request.json  # 获取 POST 请求中的 JSON 数据
    uuid = request_data.get('uuid', None)

    if uuid is None:
        return jsonify({
            'code': 400,
            'msg': '缺少 uuid 参数'
        }), 400

    data = ""

    while True:
        data_json = redis_connection.get(uuid)

        if data_json is not None:
            data = json.loads(data_json)

            redis_connection.delete(uuid)
            break
        else:
            time.sleep(0.5)

    if "error_msg" in data:
        return jsonify({
            'code': 401,
            'uuid': data["uuid"],
            'error_msg': data["error_msg"],
            'count': data["count"]
        })
    return jsonify({
        'code': 200,
        'uuid': data["uuid"],
        'data': data["data"],
        "count": data["count"]
    })


@app.route('/forecast', methods=['POST'])
def policy_compare():
    request_data = request.json  # 获取 POST 请求中的 JSON 数据
    id1 = request_data.get('id1', None)
    id2 = request_data.get('id2', None)
    id3 = request_data.get('id3', None)

    if id1 is None or id2 is None:
        return jsonify({
            'code': 400,
            'msg': '缺少 id 参数'
        }), 400

    query_result = get_date_content_by_id(id1)
    for item in query_result:
        province1 = item.get("province", "")
        pubDate1 = item.get("pubDate", "")
        content1 = item.get("short_by_content", "")
        city1 = item.get("city", "")
    query_result = get_date_content_by_id(id2)
    for item in query_result:
        province2 = item.get("province", "")
        pubDate2 = item.get("pubDate", "")
        content2 = item.get("short_by_content", "")
        city2 = item.get("city", "")
    if id3 is not None:
        query_result = get_date_content_by_id(id3)
        for item in query_result:
            province3 = item.get("province", "")
            pubDate3 = item.get("pubDate", "")
            content3 = item.get("short_by_content", "")
            city3 = item.get("city", "")

    if id3 is None:
        if province1 != province2 or city1 != city2:
            quest = province1 + ' ' + city1 + ' ' + pubDate1 + ' 发布\n' + content1 + '\n' + province2 + ' ' + city2 + ' ' + pubDate2 + ' 发布\n' + content2 + '\n' + '请你总结分析两地对于这一政策的不同之处'
        else:
            quest = province1 + ' ' + city1 + ' ' + pubDate1 + ' 发布\n' + content1 + '\n' + province2 + ' ' + city2 + ' ' + pubDate2 + ' 发布\n' + content2 + '\n' + '请你总结分析该地的政策，并预测该地对于这一政策的政策趋势'
    else:
        if province1 != province2 or city1 != city2 or province1 != province3 or city1 != city3 or province2 != province3 or city2 != city3:
            quest = (province1 + ' ' + city1 + ' ' + pubDate1 + ' 发布\n' + content1 + '\n' + province2 + ' ' + pubDate2 + ' 发布\n' + content2 + '\n' + province3 + ' ' + city3 + ' ' + pubDate3 + ' 发布\n' + content3 + '\n' + '请你总结分析三地对于这一政策的不同之处')
        else:
            quest = (province1 + ' ' + city1 + ' ' + pubDate1 + ' 发布\n' + content1 + '\n' + province2 + ' ' + city2 + ' ' + pubDate2 + ' 发布\n' + content2 + '\n' + province3 + ' ' + city3 + ' ' + pubDate3 + ' 发布\n' + content3 + '\n' + '请你总结分析该地的政策，并预测对于这一政策的政策趋势')


    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': quest}]

    response = dashscope.Generation.call(
        dashscope.Generation.Models.qwen_turbo,  # qwen_turbo / qwen_max
        messages=messages,
        result_format='message',  # set the result to be "message" format.
    )
    if response.status_code == HTTPStatus.OK:
        output = response.get("output", {})
        choices = output.get("choices", [])
        if choices:
            content = choices[0].get("message", {}).get("content")
            if content:
                # print(content)  输出 result 预览
                pass
            else:
                print("Content not found in the response.")
                return jsonify({
                    'code': 503,
                    'error_msg': "Content not found in the response"
                })
        else:
            print("Choices not found in the response.")
            return jsonify({
                'code': 503,
                'error_msg': "Content not found in the response"
            })
    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.get("request_id"), response.get("status_code"),
            response.get("code"), response.get("message")
        ))
        return jsonify({
            'code': response.get("code"),
            'error_msg': response.get("message")
        })

    if id3 is not None:
        return jsonify({
            'code': 200,
            'id1': id1,
            'id2': id2,
            'id3': id3,
            'result': content
        })

    return jsonify({
        'code': 200,
        'id1': id1,
        'id2': id2,
        'result': content
    })


def main():
    app.run(host='0.0.0.0', port=8080, debug=False, use_reloader=False, ssl_context=context, threaded=True)

main()
